/**
 * Created by no1 on 2015/8/28.
 */
'use strict';
var mysql = require('../mysql.js');
var C = require('../../config/index');
var F = require('../../common/function');
var MPosts = require('../../model/posts.js');
var MTags = require('../../model/tags.js');
var MUser = require('../../model/users.js');
var Mman = require('../../common/man.js');
var imgRule = require('../../common/imgRule.js');
var _ = require('underscore');
var _s = require('underscore.string');
var md5 = require('md5');
var request = require('koa-request');
var async_request = require('request');
var logstash = require('./../logFlow/logstash.js');
_.v = require('validator');


/**
 * @todo API37 删除主题帖、回帖
 * @param Env
 * @returns {*}
 */
exports.delPost = function*(Env, data) {
  let loginStatus = Env.I.loginStatus;
  if (!loginStatus.status) {
    return F.returnMsg(401, '登录用户才能删帖', 3);
  }
  var fields;
  if (!data) {
    fields = Env.I;
  } else {
    fields = data;
  }
  var status = parseInt(fields.status);
  var key = '';//缓存的key
  var temp = '';//缓存是否存在
  var previous_status = 0;//帖子或回帖之前的状态
  var act=fields.act||1;//act=1时，删除普通帖；act=2时，删除全部美容日记帖
  var gain=0;
  if (fields.pid) {
    var threadData = yield mysql.queryOne('SELECT tid FROM mh_thread WHERE pid=?', [fields.pid]);
    if (threadData) {
      fields.tid = threadData['tid'];
    }
  }

  if (fields.tid) {
    var tid = fields.tid;
    if (!_.v.isInt(tid) || status != 0) {
      return F.returnMsg(400, '传递的参数错误', 1);
    }
    var threadData = yield mysql.query('SELECT tid,pid,uid,status,fid,type FROM mh_thread WHERE tid=? AND uid=?', [tid, loginStatus.uid]);
    if (threadData.length == 0) {
      return F.returnMsg(400, '只能删除自己的帖子', 1);
    } else if (threadData[0]['status'] == 0) {
      return F.returnMsg(400, '该帖子已被删除', 1);
    }
    previous_status=threadData[0]['status'];
    if (threadData[0].type > 0 && threadData[0].fid == 0) {//删除美容日记贴
        if(act==2){//删除整个美容日记帖
          mysql.query('update mh_thread set `status` =? where (fid=? or tid=?) and uid=?', [status, tid,tid,loginStatus.uid]);

          //更新es数据库
          let tid_data = yield mysql.query('select tid from mh_thread where (fid=? or tid=?) and uid=?',[tid,tid,loginStatus.uid]);
          let tid_array=[];
          for(let record of tid_data){
            tid_array.push(record.tid);
          }
          let json = {
            uid: loginStatus.uid,
            tid: tid_array,
            status:0,
            action:'edit'
          };
          logstash.article(json);
        }else{//删除美容日记贴首贴,只将首帖发的内容删除
          mysql.query('update mh_post set `status`=? where tid=? and `first`=1 and uid=?',[status,tid,loginStatus.uid]);
        }
    } else {//删除普通帖，美容跟帖这里也可以当成是普通帖
      mysql.query('update mh_thread set `status`=? where tid=? and uid=?', [status, tid, loginStatus.uid]);
      //更新es数据库
      let json = {
        uid: loginStatus.uid,
        tid: tid,
        status:0,
        action:'edit'
      };
      logstash.article(json);
    }
    if (previous_status == 1) {//如果是从有效转为无效
      if (parseInt(threadData[0].fid) > 0 || (parseInt(threadData[0].fid) == 0 && parseInt(threadData[0].type) > 0)) {
        let daily_fid = tid;
        let tidArr = [];
        if (act == 2 && parseInt(threadData[0].fid) == 0) {//删除整个美容日记帖的情况
          mysql.query('update mh_thread_extend set dailyNum=0 where tid=? and uid=?', [tid, loginStatus.uid]);
          mysql.query('update mh_user_info set plasticthreads=plasticthreads-1 where uid=?', [loginStatus.uid]);
          key = C.redisPre.user_info;
          key = _.str.sprintf(key, loginStatus.uid);
          temp = yield F.redisCo.EXISTS(key);
          if (temp == 1) {
            F.redisClient.HINCRBY(key, 'plasticthreads', -1);//发帖人发美容日记帖数-1
          }
        } else {//删除单一日记帖的情况
          daily_fid = parseInt(threadData[0]['fid']);
          if (parseInt(threadData[0].type) > 0) {//如果删除首帖，则自己为父贴
            daily_fid = tid;
          }
          mysql.query('update mh_thread_extend set dailyNum=dailyNum-1 where tid=?', [daily_fid]);
        }
        let daily_tid_arr = yield  mysql.query('SELECT tid from mh_thread where tid=? or fid=? ORDER BY tid ', [daily_fid, daily_fid]);
        if (daily_tid_arr.length > 0) {
          for (var i in daily_tid_arr) {
            tidArr.push(daily_tid_arr[i].tid);
          }
          var key = C.redisPre.thread_info;
          var expire = C.redisPre.thread_ttl;
          if (act == 2 && parseInt(threadData[0].fid) == 0) {
            yield F.redisCo.mhupdatethread(4, key, expire, 0, 'dailyNum', tidArr);
          } else {
            yield F.redisCo.mhincreasethreadfield(4, key, expire, -1, 'dailyNum', tidArr);
          }
        }
      }
    }
    //准备要删除的tid数组
    var delete_tid_arr=[tid];

    //判断是否只是删除美容日记帖首页
    if(threadData[0].type > 0 && threadData[0].fid == 0){
      if (act == 1) {
        gain=yield F.generateIntegralLog(parseInt(loginStatus.uid), 4, tid);//删除帖子成功后扣积分
        return F.returnMsg(200, {act: '删除成功', e: gain}, 4);
      }else if(act==2){//删除整个美容日记帖
        let dailyThread=yield  mysql.query('SELECT tid from mh_thread where fid=? and status <>0 ORDER BY tid ',[tid]);
        if (dailyThread && dailyThread.length > 0) {
          for(let thread of dailyThread){
            delete_tid_arr.push(thread.tid);
          }
        }
      }
    }

    for(let thread_id of delete_tid_arr){
      tid=thread_id;
      var updateThreadCache = {};
      updateThreadCache.status = 0;
      yield F.updateThreadCache(parseInt(tid), updateThreadCache);//更新帖子缓存
      mysql.query("update mh_post set `status`=? where pid=?", [status, threadData[0]['pid']]);//更新回帖操作
      mysql.query("delete from mh_dynamic_info where tid=?", [tid]);//删除动态信息

      //当删除全部美容贴的时候，取得即将要删除的tid
      if(threadData[0].type > 0 && threadData[0].fid == 0 && act==2){
        let threadStatus=yield  mysql.queryOne('SELECT status from mh_thread where tid=?',[tid]);
        if(threadStatus){
          previous_status=threadStatus['status'];
        }
      }

      if(previous_status==1) {
        var tagIdArr = [];//帖子标签id数组
        var threadTag = yield mysql.query('SELECT tagsid FROM mh_thread_tags WHERE tagstype=1 and tid=?', [tid]);//帖子标签
        if (threadTag.length > 0) {
          for (var i in threadTag) {
            tagIdArr.push(threadTag[i].tagsid);
          }
        }
        var favUserArr = [];//收藏帖子用户数组
        var threadFav = yield mysql.query('SELECT uid FROM mh_fav WHERE tid=?', [tid]);
        if (threadFav.length > 0) {
          for (var i in threadFav) {
            favUserArr.push(threadFav[i].uid);
          }
        }
        var likeUserArr = [];//点赞帖子用户数组
        var threadLike = yield mysql.query('SELECT DISTINCT uid FROM mh_likes WHERE tid=? and first=1', [tid]);
        if (threadLike.length > 0) {
          for (var i in threadLike) {
            likeUserArr.push(threadLike[i].uid);
          }
        }
        if (tagIdArr.length > 0) {
          mysql.query("UPDATE mh_tags set tagcount=tagcount-1 WHERE tagid in(" + tagIdArr.join(',') + ")");//更新帖子标签的帖子数
          for (var i in tagIdArr) {
            //更新标签信息开始
            key = C.redisPre.tag_info;
            key = _.str.sprintf(key, parseInt(tagIdArr[i]), 1);
            temp = yield F.redisCo.EXISTS(key);
            if (temp == 1) {
              F.redisClient.HINCRBY(key, 'tagcount', -1);//标签使用次数-1
            }
            //更新标签信息结束
          }
        }
        if (favUserArr.length > 0) {
          mysql.query("UPDATE mh_user_info set tfavtimes=tfavtimes-1 WHERE uid in(" + favUserArr.join(',') + ")");//更新帖子收藏人的收藏帖子数
          for (var i in favUserArr) {
            //更新收藏人信息开始
            key = C.redisPre.user_info;
            key = _.str.sprintf(key, parseInt(favUserArr[i]));
            temp = yield F.redisCo.EXISTS(key);
            if (temp == 1) {
              F.redisClient.HINCRBY(key, 'tfavtimes', -1);//收藏用户收藏数-1
            }
            //更新收藏人信息结束
          }
        }
        mysql.query("UPDATE mh_user_info set threads=threads-1,posts=posts-1,beliked=beliked-" + likeUserArr.length + " WHERE uid=?", [threadData[0]['uid']]);//更新发帖人的发帖数，回帖数
        //更新发帖人信息开始
        key = C.redisPre.user_info;
        key = _.str.sprintf(key, parseInt(threadData[0]['uid']))
        temp = yield F.redisCo.EXISTS(key);
        if (temp == 1) {
          F.redisClient.HINCRBY(key, 'threads', -1);//发帖人发帖数-1
          F.redisClient.HINCRBY(key, 'posts', -1);//发帖人回帖数-1
        }
        //更新发帖人信息结束

        //更新帖子的投诉为已处理开始
        mysql.query('UPDATE mh_post_complain SET `status`=1 WHERE tid=?', [tid]);
        //更新帖子的投诉为已处理结束

        //重新写最新帖子缓存开始
        key = C.redisPre.lists_news;
        key = _.str.sprintf(key, 0);
        temp = yield F.redisCo.EXISTS(key);
        if (temp == 1) {
          F.redisClient.DEL(key);
          yield F.newestThreadListCache();
        }
        //重新写最新帖子缓存结束

        //重新写发帖人发帖缓存开始
        key = C.redisPre.lists_user;
        key = _.str.sprintf(key, parseInt(threadData[0]['uid']));
        temp = yield F.redisCo.EXISTS(key);
        if (temp == 1) {
          F.redisClient.DEL(key);
          yield F.usersThreadCache([parseInt(threadData[0]['uid'])]);
        }
        //重新写发帖人发帖缓存结束

        gain += yield F.generateIntegralLog(parseInt(loginStatus.uid), 4, tid);//删除帖子成功后扣积分
      }else if(previous_status==2){//之前状态为2时，已经被扣过分了
        gain += yield F.generateIntegralLog(parseInt(loginStatus.uid), 4, tid,true);//删除帖子成功后扣积分,第四个参数标识是否不扣分，为真时不会扣除
      }
    }
  } else if (fields.pid) {
    var pid = fields.pid;
    if (!_.v.isInt(pid) || status != 0) {
      return F.returnMsg(400, '传递的参数错误', 1);
    }
    var postData = yield mysql.query('SELECT tid,status,vest FROM mh_post WHERE pid=? AND uid=?', [pid, loginStatus.uid]);
    if (postData.length == 0) {
      return F.returnMsg(400, '只能删除自己的帖子', 1);
    } else if (postData[0]['status'] == 0) {
      return F.returnMsg(400, '该帖子已被删除', 1);
    }
    previous_status=postData[0]['status'];
    var affRow = yield mysql.query('update mh_post set `status`=? where pid=?', [status, pid]);
    if (affRow.affectedRows > 0) {
      mysql.query("delete from mh_dynamic_info where pid=?", [pid]);//删除动态信息
      if (previous_status == 1) {
        key = C.redisPre.thread_info;
        key = _.str.sprintf(key, parseInt(postData[0]['tid']));
        var temp = yield F.redisCo.EXISTS(key);
        if (postData[0]['vest'] == 1) {
          // 马甲贴
          mysql.query('UPDATE mh_thread SET replies=replies-1 WHERE tid=?', [postData[0]['tid']]);//
        } else {
          // 用户贴
          mysql.query('UPDATE mh_thread SET userreplies=userreplies-1,replies=replies-1 WHERE tid=?', [postData[0]['tid']]);//
        }
        //更新帖子信息开始
        if (temp == 1) {
          //更新帖子的最近三个回帖开始
          var postUsers = JSON.stringify([]);
          var postUserseData = yield MPosts.getPostUsers({"tid": parseInt(postData[0]['tid'])});
          if (postUserseData.length > 0) {
            postUsers = JSON.stringify(postUserseData);
          }
          var updateThreadCache = {};
          updateThreadCache.postusers = postUsers;
          yield F.updateThreadCache(parseInt(postData[0]['tid']), updateThreadCache);//更新帖子缓存
          //更新帖子的最近三个回帖结束
          F.redisClient.HINCRBY(key, 'replies', -1);//帖子回复数-1
        }
        //更新帖子信息结束

        //更新帖子的投诉为已处理开始
        mysql.query('UPDATE mh_post_complain SET `status`=1 WHERE pid=?', [pid]);
        //更新帖子的投诉为已处理结束
        gain = yield F.generateIntegralLog(parseInt(loginStatus.uid), 16, pid);//删除回帖成功后扣积分
      }else if(previous_status==2){//为2时已经被扣过分了
        gain = yield F.generateIntegralLog(parseInt(loginStatus.uid), 16, pid,true);//删除回帖成功后扣积分
      }
    }
  } else {
    return F.returnMsg(400, '选择要删除的帖子', 1);
  }
  return F.returnMsg(200, {act: '删除成功', e: gain}, 4);
};
